package com.kavenka.zhufengfm.app.utils;

import java.io.*;

/**
 * Created by kavenka on 2015/9/25 0025.
 */
public class StreamUtil {
    private StreamUtil(){
    }

    public static void close(Object stream){
        if (stream != null) {
            try {
                if (stream instanceof InputStream){
                    ((InputStream) stream).close();
                }else if (stream instanceof OutputStream){
                    ((OutputStream) stream).close();
                }else if (stream instanceof Reader){
                    ((Reader) stream).close();
                }else if (stream instanceof Writer) {
                    ((Writer) stream).close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 读取字节流
     * @param in
     * @return
     */
    public static byte[] readStream(InputStream in){
        byte[] ret=null;
        if (in != null) {
            ByteArrayOutputStream bout=new ByteArrayOutputStream();
            try {
                readStream(in, bout);
                ret = bout.toByteArray();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                close(bout);
            }
        }
        return ret;
    }
    private static long readStream(InputStream in, OutputStream out) throws IOException {
        long ret=0;
        if (in!=null&&out!=null){
            byte[] buf=new byte[128];
            int len=0;
            while(true){
                len=in.read(buf);
                if (len==-1){
                    break;
                }
                out.write(buf,0,len);
                ret+=len;
            }
            buf=null;
        }
        return ret;
    }
}
